﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[CountInvRepeatsInRepExpAdv] 
(
	@InvId int
)
RETURNS int
AS
BEGIN
	DECLARE @C int
	SET @C = 0
	
	SELECT @C = COUNT(*) FROM (SELECT pu.NAME
	FROM INVOICE_OUT AS io INNER JOIN
         INVOICE_OUT_ITEM AS ioi ON io.ID = ioi.INVOICE_OUT_ID 
         INNER JOIN
         VIEW_SEARCH_P_U_FOR_FORMS AS pu ON pu.ID = ioi.PRODUCT_UNIT_ID 
    WHERE
		(io.ID = @InvID) AND (pu.NSI_PRODUCT_STATE_ID <= 3) AND (ISNULL(pu.INVOICE_IN_SUM, 0) - ISNULL(pu.PAYMENT_IN_SUM_CUR, 0) > 0)
	GROUP BY pu.NAME) as t
	
	IF @C = 0
	BEGIN
		SET @C = 1
	END
	RETURN @C
END